<template>
  <div class="myTable-wrap" :id="myTableId">
    <el-table :data="tableData" :height="tableHeight" :size="options.size || ''">
      <el-table-column
        v-for="item in columns"
        :key="item.name"
        :prop="item.name"
        :label="item.title || ''"
        :width="item.width || ''"
        :min-width="item.minWidth || ''"
        :fixed="item.fixed || false"
      />
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, type PropType } from 'vue'
import type { TableOptionType } from './myTableTypes'
import { getRandomStr } from '@/utils/tools'
import { request } from '@/utils/request'

const props = defineProps({
  options: {
    type: Object as PropType<TableOptionType>,
    default: () => {
      return {}
    }
  }
})

const emit = defineEmits(['getSearchData'])

const columns = computed(() => {
  return props.options.columns || []
})

/** 组件随机id */
const myTableId = ref('myTableId-' + getRandomStr())

/** 表格高度 */
const tableHeight = ref(500)
/** 获取表格高度 */
const getTableHeight = () => {
  // 当前元素
  const element: any = document.getElementById(myTableId.value)
  // 父元素
  const parent = element.parentNode
  // 父元素的所有子元素高度之和，除去当前元素
  let childrenHeight = 0
  for (let i = 0; i < parent.children.length; ++i) {
    if (parent.children[i].id !== myTableId.value) {
      childrenHeight += parent.children[i].offsetHeight
    }
  }
  // 计算高度差，留有4px的富裕
  tableHeight.value = parent.offsetHeight - childrenHeight - 4
}

/** 表格数据 */
const tableData = ref<any[]>([])
/** 获取表格数据 */
const getTableData = () => {
  if (props.options.url) {
    request({
      url: props.options.url,
      data: {}
    }).then((res) => {
      tableData.value = res || []
      // 写到这里了
    })
  }
  // 使用本地数据
}

onMounted(() => {
  getTableData()
  getTableHeight()
  // 监听页面变化，设置表格高度
  window.addEventListener('resize', getTableHeight)
})

onUnmounted(() => {
  // 取消监听
  window.removeEventListener('resize', getTableHeight)
})
</script>

<style lang="less" scoped>
.myTable-wrap {
}
</style>
